﻿using System;
using System.Globalization;
using System.Web.UI.WebControls;
using ContractManagementSystem.BusinessLogicLayer;
using ContractManagementSystem.EntityObjects;

namespace ContractManagementSystem.Presentation.ReportManagement
{
    public partial class ReportTimesheet : System.Web.UI.Page
    {
        private int _roleId;
        private string _user;

        protected void Page_Load(object sender, EventArgs e)
        {
            CheckUserPermission();

            if (Session["RoleId"] != null)
            {
                if (!IsPostBack)
                {
                    BindData();
                    BindDataContract();
                }
            }
        }
        protected void Page_PreRender(object sender, EventArgs e)
        {
            ButtonSearchClick(null, null);
            ListViewTimesheet.DataBind();
        }
        private void BindData()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _user = Session["UserName"].ToString();

            if (_roleId == 1)
            {
                var result = TimesheetLogic.SelectDataTimesheet();
                Session["SOURCE_TIMESHEET_TABLE"] = result;
                ListViewTimesheet.DataSource = result;
            }
            else if(_roleId==4)
            {
                var result = TimesheetLogic.SelectDataTimesheetByConsultant(_user);
                Session["SOURCE_TIMESHEET_TABLE"] = result;
                ListViewTimesheet.DataSource = result;
            }
            ListViewTimesheet.DataBind();
        }

        protected void BindDataContract()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _user = Session["UserName"].ToString();

            if (_roleId == 1)
            {
                DropDownListContractTitle.DataSource = ContractLogic.ListActiveContracts();
            }
            else if(_roleId==4)
            {
                DropDownListContractTitle.DataSource = ContractLogic.ListActiveContractsByConsultant(_user);
            }

            DropDownListContractTitle.DataTextField = "ContractNumber";
            DropDownListContractTitle.DataValueField = "ContractNumber";
            DropDownListContractTitle.DataBind(); 
            DropDownListContractTitle.Items.Insert(0,new ListItem("All","All"));
        }

        /// <summary>
        /// Filter search timesheets
        /// </summary>
        protected void FilterTimesheet()
        {
            _roleId = int.Parse(Session["RoleId"].ToString(), CultureInfo.InvariantCulture);
            _user = Session["UserName"].ToString();

            var dropConsultantNumber = DropDownListContractTitle.Text;
            var dropTimesheetStatus = DropDownListStatus.Text;
            var fromDate = textFromDate.Text;
            var toDate = textToDate.Text;
            var sort = string.Empty;
            if (_roleId == 1)
            {
                var result = TimesheetLogic.SearchTimesheet(dropConsultantNumber, dropTimesheetStatus, fromDate, toDate,
                                                            sort);
                if (result == null)
                {
                    return;
                }
                Session["SOURCE_TIMESHEET_TABLE"] = result;
                ListViewTimesheet.DataSource = result;
            }
            else if(_roleId==4)
            {
                var result = TimesheetLogic.SearchTimesheetByConsultant(dropConsultantNumber, dropTimesheetStatus, fromDate, toDate,sort,_user);
                if (result == null)
                {
                    return;
                }
                Session["SOURCE_TIMESHEET_TABLE"] = result;
                ListViewTimesheet.DataSource = result;         
            }
            ListViewTimesheet.DataBind();
        }

        protected void ButtonSearchClick(object sender, EventArgs e)
        {
            if (!string.IsNullOrEmpty(textFromDate.Text))
            {
                DateTime dt;
                if (!DateTime.TryParseExact(textFromDate.Text, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
                {
                    labelResultSearch.Text = "Format From date InCorrect";
                    return;
                }
            }
            if(!string.IsNullOrEmpty(textToDate.Text))
            {
                DateTime dt;
                if (!DateTime.TryParseExact(textToDate.Text, "MM/dd/yyyy", null, DateTimeStyles.None, out dt))
                {
                    labelResultSearch.Text = "Format To date InCorrect";
                    return;
                }
            }
            FilterTimesheet();
        }

        protected void CreateButtonReportClick(object sender, EventArgs e)
        {
            Response.Redirect("ShowReportTimesheet.aspx");
        }

        // Check user's permissions
        private void CheckUserPermission()
        {
            var userName = CommonLogic.ConvertToString(Session["UserName"]);
            const int functionId = (int)FunctionList.AllReport;

            var urlToCome = Page.Master.ResolveUrl("Presentation/AuthorizationError.aspx");

            AuthorizationChecker.IsValidAuthorization(userName, functionId, Response, urlToCome);
        }
    }
}
